package com.yami.shop.multishop.controller;

import cn.hutool.core.lang.Snowflake;
import com.yami.shop.bean.app.param.PayGasShopUserParam;
import com.yami.shop.bean.app.param.PayUserParam;
import com.yami.shop.bean.enums.PayEntry;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.common.enums.PayType;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.manager.impl.PayManager;
import com.yami.shop.nft.common.model.NftGasDeploy;
import com.yami.shop.nft.common.service.NftGasDeployService;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.*;
import com.yami.shop.user.common.model.UserGasLog;
import com.yami.shop.user.common.service.UserGasLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Tag(name = "GAS充值支付接口")
@RestController
@RequestMapping("/m/gasNft")
@AllArgsConstructor
public class ShopPayGasController {

    private final UserGasLogService userGasLogService;
    private final Snowflake snowflake;
    private final PayManager payManager;
    private final PayInfoService payInfoService;
    private final ShopConfig shopConfig;
    private final ShopDetailService shopDetailService;
    public static final int SYS_MONEY_UNIT = 100;
    private final NftGasDeployService nftGasDeployService;
    private final SmsLogService smsLogService;
    /**
     *  店铺 GAS充值支付接口
     */
    @PostMapping("/shopPayGas")
    @Operation(summary =  "店铺GAS充值接口", description = "店铺GAS充值接口")
    @SneakyThrows
    public ServerResponseEntity<?> payGas(HttpServletResponse httpResponse, @RequestBody PayGasShopUserParam payGasShopUserParam) {
        ShopDetail shopDetail = shopDetailService.getById(SecurityUtils.getShopUser().getShopId());

        if (payGasShopUserParam.getPayType().equals(PayType.SCOREPAY.value())){
            // 请使用微信或支付宝进行支付
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.payType.error"));
        }
        if (!smsLogService.checkValidCode(shopDetail.getReceiveMobile(), payGasShopUserParam.getValidCode(), SendType.VALID)) {
            // 验证码有误或已过期
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.code.error"));
        }

        Double gasMoney = 0.00;
        Long gasId = 0l;
        Integer gasNum = 0;
        if(payGasShopUserParam.getDeployId() == -1 ){
            // 等于 -1 自定义次数
            // 计算金额 获取折扣比例
            ShopDetail byId = shopDetailService.getById(SecurityUtils.getShopUser().getShopId());
            if(ObjectUtils.isEmpty(byId)){
                throw new YamiShopBindException("店铺折扣获取失败");
            }
            if(ObjectUtils.isEmpty(byId.getDiscount())){
                byId.setDiscount(0.0000);
            }
            BigDecimal money = new BigDecimal(byId.getDiscount()).divide(new BigDecimal(SYS_MONEY_UNIT));
            money = money.setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal b = new BigDecimal(0.00);
            Double total = 0.00;
            if(money.compareTo(b) == 0){
                total = Double.valueOf(payGasShopUserParam.getGasNum());
            }else{
                total = money.doubleValue() * Double.valueOf(payGasShopUserParam.getGasNum());
            }
            BigDecimal bigDecimal = new BigDecimal(total).setScale(2,BigDecimal.ROUND_HALF_UP); // 四舍五入 保留两位小数
            gasMoney = bigDecimal.doubleValue();
            gasId = -1l;
            gasNum = payGasShopUserParam.getGasNum();
        }else{
            //充值能量选项
            NftGasDeploy gasListById = nftGasDeployService.getGasListById(payGasShopUserParam.getDeployId());
            if (Objects.isNull(gasListById)) {
                // 当前余额充值选项已被删除
                throw new YamiShopBindException("yami.user.blance.not.exist");
            }
            // 套餐金额
            BigDecimal money = new BigDecimal(gasListById.getNftSpecialPrice()).divide(new BigDecimal(SYS_MONEY_UNIT));
            money = money.setScale(2, BigDecimal.ROUND_HALF_UP);
            gasMoney = money.doubleValue();
            gasId = payGasShopUserParam.getDeployId().longValue();
            gasNum = gasListById.getNftNum();
        }

        // 使用雪花算法生成支付单号
        String payNo = String.valueOf(snowflake.nextId());
        Date now = new Date();
        //生成GAS余额充值日志
        UserGasLog userGasLog = new UserGasLog();
        userGasLog.setCreateTime(now);
        userGasLog.setIoType(0); // 收支类型 0支出 1收入
        userGasLog.setType(7);   // gas店铺 充值类型
        userGasLog.setIsPayed(0);  // 0未支付
        userGasLog.setPayNo(payNo);  // 支付单号
        userGasLog.setUserId(SecurityUtils.getShopUser().getShopId().toString()); // 店铺充值 存店铺id
        userGasLog.setGasId(gasId);  //gas id
        userGasLog.setGasBalance(gasMoney);
        userGasLog.setTabStatus(0); //默认0未发送
        userGasLog.setGasNum(gasNum);  // 次数
//        userGasLog.setChainTab(payGasShopUserParam.getChain());
        userGasLogService.save(userGasLog);

        PayUserParam payUserParam = new PayUserParam();
        payUserParam.setNeedAmount(userGasLog.getGasBalance());
        payUserParam.setPayNo(payNo);
        payUserParam.setOrderIds(userGasLog.getGasLogId());
        payUserParam.setPayType(payGasShopUserParam.getPayType());
        PayInfoDto payInfo = payInfoService.payGas(SecurityUtils.getShopUser().getShopId().toString(), payUserParam);
        payInfo.setBizUserId(SecurityUtils.getShopUser().getShopId().toString());
        payInfo.setPayType(payGasShopUserParam.getPayType());
        payInfo.setApiNoticeUrl("/notice/pay/" + PayEntry.GAS_RECHARGE.value() + "/" + payGasShopUserParam.getPayType());
        payInfo.setReturnUrl(payGasShopUserParam.getReturnUrl());
        payInfo.setPayUserId(shopDetail.getShopXsUserId());
        payInfo.setReceiveUserId(shopConfig.getHnaPay().getMerId());
        payInfo.setXsFastPaymentOneParam(payGasShopUserParam.getXsFastPaymentOneParam());
        payInfo.setPayUserType("1");
        return payManager.doPay(httpResponse, payInfo);
    }

    public static void main(String[] args) {
        BigDecimal money = new BigDecimal(0.0000).divide(new BigDecimal(SYS_MONEY_UNIT));
        money = money.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println("----"+money);
        BigDecimal b = new BigDecimal(0.00);
        if(money.compareTo(b) == 0){
            System.out.println("--===");
        }
        Double total = money.doubleValue() * Double.valueOf(321);
        System.out.println("-"+total);
        BigDecimal bigDecimal = new BigDecimal(total).setScale(2,BigDecimal.ROUND_HALF_UP);
    }
}
